<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/js-base64@3.6.0/base64.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background-color: #f5f5f5;
            color: #333;
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
        }

.file-container {
    padding: 0;
            max-width: none;
            margin: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }


.file-list {
    background: white;
    border-radius: 0;
    box-shadow: none;
            overflow: hidden;
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
        }

        .file-list-wrapper {
            flex: 1;
            overflow: hidden;
        }

.file-table {
    width: calc(100% - 40px); /* 左右各留20px */
    margin: 0 20px;
    border-collapse: collapse;
    table-layout: fixed;
    overflow: hidden;
}

        .file-table thead {
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .file-table tbody {
            max-height: calc(100vh - 200px);
            overflow-y: auto;
        }

        .file-table th {
            background: #f8f9fa;
            padding: 12px 16px;
            text-align: left;
            font-weight: 600;
            color: #666;
            border-bottom: 1px solid #dee2e6;
            white-space: nowrap;
            font-size: 13px;
        }

        .file-table th:first-child {
            width: 5%;
        }

        .file-table th:nth-child(2) {
            width: 30%;
        }

        .file-table th:nth-child(3) {
            width: 15%;
            text-align: left !important;
        }

        .file-table th:nth-child(4) {
            width: 15%;
        }

        .file-table th:nth-child(5) {
            width: 20%;
            text-align: center !important; /* 操作列居中对齐 */
        }

        /* 文件名列特殊处理 */
        .file-table td:nth-child(2) {
            overflow: visible;
            white-space: normal;
        }

        /* 大小列左对齐 */
        .file-table td:nth-child(3) {
            text-align: left !important;
        }

        /* 操作列居中对齐 */
        .file-table td:nth-child(5) {
            text-align: center !important;
        }

        .file-table td {
            padding: 8px 16px;
            border-bottom: 1px solid #f0f0f0;
            vertical-align: middle;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 13px;
        }

        .file-table tr:hover {
            background: #f8f9fa;
        }

        .file-item {
            display: flex;
            align-items: center;
            gap: 12px;
            overflow: hidden;
        }

        .file-icon {
            font-size: 20px;
            width: 24px;
            text-align: center;
        }

        .file-name {
            font-weight: 500;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            flex: 1;
            min-width: 0;
            text-shadow: none;
        }

        .file-size {
            color: #666;
            font-size: 14px;
            text-align: left;
        }


        .file-date {
            color: #666;
            font-size: 14px;
            white-space: nowrap;
        }

        .file-actions {
            display: flex;
            gap: 8px;
            flex-wrap: nowrap;
            overflow: hidden;
        }

        .action-btn {
            padding: 4px 8px;
            border: none;
            background: #f8f9fa;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            color: #666;
            transition: all 0.2s;
            white-space: nowrap;
            min-width: 40px;
        }

        .action-btn:hover {
            background: #e9ecef;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-icon {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .page-header { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; background: white; border-bottom: 1px solid #e9ecef; }
        .page-title { margin: 0; font-size: 18px; font-weight: 600; color: #333; }
        .batch-actions { display: flex; align-items: center; gap: 12px; }
        .batch-info { color: #666; font-size: 14px; font-weight: 500; }
        .action-buttons { display: flex; gap: 8px; }
        .action-item { position: relative; cursor: pointer; transition: all 0.2s; padding: 4px; border-radius: 6px; }
        .action-item:hover { background: #f8f9fa; }
        .action-icon { width: 22px; height: 22px; border: none; border-radius: 50%; background: #f8f9fa; font-size: 12px; cursor: pointer; transition: all 0.2s; display: flex; align-items: center; justify-content: center; }
        .action-icon:hover { transform: scale(1.1); }
.action-icon.download { background: #e3f2fd; color: #1976d2; }
.action-icon.delete { background: #ffebee; color: #d32f2f; }
.action-icon.cancel { background: #f5f5f5; color: #757575; }
.action-icon.create { background: #e8f5e8; color: #2e7d32; }
.action-icon.upload { background: #fff3e0; color: #f57c00; }
.action-icon.rename { background: #f3e5f5; color: #7b1fa2; }
.action-icon.share { background: #e8f5e8; color: #2e7d32; }
        
        /* 面包屑样式 - 作为页面标题 */
        .breadcrumb {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
        
        .breadcrumb-item {
            cursor: pointer;
            color: #333; /* 名字不使用蓝色 */
            text-decoration: none;
            margin-right: 8px;
        }
        
        .breadcrumb-item:hover {
            text-decoration: none; /* 悬停不加下划线，保持简洁 */
        }
        
        .breadcrumb-item.active {
            color: #333;
            cursor: default;
        }
        
        .breadcrumb-item.active:hover {
            text-decoration: none;
        }
        
        .breadcrumb-separator {
            margin: 0 8px;
            color: #999;
        }
        
        /* 悬浮提示样式 */
        .action-item::after {
            content: attr(data-tooltip);
            position: absolute;
            bottom: -30px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s, visibility 0.3s;
            z-index: 1000;
            pointer-events: none;
        }
        .action-item.show-tooltip::after {
            opacity: 1;
            visibility: visible;
        }

        /* 模态框样式 */
        .modal { 
            position: fixed; 
            z-index: 1000; 
            left: 0; 
            top: 0; 
            width: 100%; 
            height: 100%; 
            background-color: rgba(0,0,0,0.5); 
            display: flex;
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.3s ease-out;
            backdrop-filter: blur(2px);
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .modal-content { 
            background-color: #ffffff; 
            margin: 0; 
            padding: 0; 
            border: none; 
            border-radius: 20px; 
            width: 420px; 
            box-shadow: 0 16px 48px rgba(0,0,0,0.2); 
            max-height: 90vh;
            overflow: hidden;
            animation: modalSlideIn 0.3s ease-out;
        }
        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px) scale(0.95);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        .modal-header { 
            padding: 24px 28px 18px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .modal-header h3 { 
            margin: 0; 
            font-size: 20px; 
            font-weight: 600; 
            color: #ffffff; 
            letter-spacing: 0.5px;
        }
        .close { 
            color: rgba(255, 255, 255, 0.9); 
            font-size: 28px; 
            font-weight: 300; 
            cursor: pointer; 
            line-height: 1; 
            transition: all 0.2s;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.15);
        }
        .close:hover { 
            background: rgba(255, 255, 255, 0.25);
            transform: rotate(90deg);
        }
        .modal-body { 
            padding: 24px 28px; 
        }
        .modal-footer { 
            padding: 18px 28px 24px; 
            display: flex; 
            justify-content: flex-end; 
            gap: 12px; 
            background: #fafafa;
        }
        .form-group { 
            margin-bottom: 16px; 
        }
        .form-group label { 
            display: block; 
            margin-bottom: 8px; 
            font-weight: 500; 
            color: #333; 
        }
        .form-group input { 
            width: 100%; 
            padding: 10px 12px; 
            border: 1px solid #ddd; 
            border-radius: 4px; 
            font-size: 14px; 
            box-sizing: border-box; 
        }
        .form-group input:focus { 
            outline: none; 
            border-color: #1976d2; 
            box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2); 
        }
        .btn { 
            padding: 10px 24px; 
            border: none; 
            border-radius: 8px; 
            cursor: pointer; 
            font-size: 14px; 
            font-weight: 500;
            transition: all 0.3s ease;
            letter-spacing: 0.3px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .btn-primary { 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white; 
        }
        .btn-primary:hover { 
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
        .btn-primary:active {
            transform: translateY(0);
        }
        .btn-secondary { 
            background-color: white; 
            color: #666;
            border: 2px solid #e0e0e0; 
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .btn-secondary:hover { 
            background-color: #f8f8f8; 
            border-color: #ccc;
        }
        
        /* 分享设置专用样式 */
        .share-form-item {
            display: flex;
            align-items: center;
            padding: 14px 18px;
            margin-bottom: 10px;
            background: #f8f9fa;
            border-radius: 12px;
            border: 2px solid transparent;
            transition: all 0.3s ease;
        }
        .share-form-item:hover {
            background: #f0f2f5;
            border-color: #e0e7ff;
        }
        .share-form-item label {
            flex: 0 0 100px;
            margin: 0;
            font-weight: 500;
            color: #495057;
            font-size: 14px;
        }
        .share-form-item select {
            flex: 1;
            padding: 10px 14px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            transition: all 0.3s ease;
            color: #333;
            font-weight: 500;
        }
        .share-form-item select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .share-form-item input[type="checkbox"] {
            width: 22px;
            height: 22px;
            margin: 0;
            cursor: pointer;
            accent-color: #667eea;
        }
        .share-form-item .checkbox-label {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 10px;
            margin: 0;
            cursor: pointer;
            user-select: none;
        }
        .share-form-item .checkbox-label span {
            font-size: 15px;
            color: #495057;
            font-weight: 500;
        }
        .share-form-item .checkbox-label:hover span {
            color: #667eea;
        }

        /* 上传弹窗样式 */
        .upload-content {
            width: 500px;
            max-width: 90vw;
        }
        
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #fafafa;
        }
        
        .upload-area:hover {
            border-color: #1976d2;
            background: #f0f8ff;
        }
        
        .upload-area.dragover {
            border-color: #1976d2;
            background: #e3f2fd;
        }
        
        .upload-icon {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.6;
        }
        
        .upload-text {
            font-size: 16px;
            color: #333;
            margin-bottom: 8px;
        }
        
        .upload-hint {
            font-size: 14px;
            color: #666;
        }
        
        .file-list {
            margin-top: 20px;
        }
        
        .file-list-header {
            font-weight: 500;
            color: #333;
            margin-bottom: 12px;
        }
        
        .upload-file-item {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            background: #f8f9fa;
            border-radius: 4px;
            margin-bottom: 8px;
        }
        
        .upload-file-item:last-child {
            margin-bottom: 0;
        }
        
        .file-icon {
            margin-right: 12px;
            font-size: 16px;
        }
        
        .file-info {
            flex: 1;
        }
        
        .file-name {
            font-weight: 500;
            color: #333;
            text-shadow: none;
        }
        
        .file-size {
            font-size: 12px;
            color: #666;
        }
        
        .file-remove {
            color: #d32f2f;
            cursor: pointer;
            font-size: 18px;
            margin-left: 8px;
        }
        
        .upload-progress {
            margin-top: 20px;
        }
        
        .progress-bar {
            width: 100%;
            height: 8px;
            background: #f0f0f0;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 8px;
        }
        
        .progress-fill {
            height: 100%;
            background: #1976d2;
            transition: width 0.3s ease;
            width: 0%;
        }
        
        .progress-text {
            text-align: center;
            font-size: 14px;
            color: #666;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 0;
            padding: 20px;
            flex-shrink: 0;
            background: white;
            border-radius: 0;
            box-shadow: none;
            border-top: none;
        }

        .page-btn {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }

        .page-btn:hover:not(:disabled) {
            background: #f8f9fa;
            border-color: #007bff;
        }

        .page-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            background: #f5f5f5;
        }

        .page-btn.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }

        .page-btn:active:not(:disabled) {
            transform: translateY(1px);
        }

        .page-info {
            color: #666;
            font-size: 14px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .file-container {
                padding: 0;
            }
            
            .file-table th,
            .file-table td {
                padding: 6px 12px;
                font-size: 12px;
            }
            
            .file-table th:nth-child(4),
            .file-table td:nth-child(4) {
                display: none;
            }
            
            .file-table th:nth-child(2) {
                width: 50%; /* 从60%减少到50% */
            }
            
            .file-table th:nth-child(3) {
                width: 20%;
            }
            
            .file-table th:nth-child(5) {
                width: 30%; /* 从20%增加到30% */
                text-align: center !important;
            }
            
            .file-action-icon {
                width: 20px;
                height: 20px;
                font-size: 10px;
            }
        }

        @media (max-width: 480px) {
            .file-table th:nth-child(3),
            .file-table td:nth-child(3) {
                display: none;
            }
            
            .file-table th:nth-child(2) {
                width: 70%;
            }
            
            .file-table th:nth-child(5) {
                width: 30%;
            }
            
            .file-actions {
                flex-direction: column;
                gap: 4px;
            }
            
            .file-action-icon {
                width: 18px;
                height: 18px;
                font-size: 9px;
            }
        }

        /* 高亮关键词样式：黄色背景、加粗文字 */
        .highlight-keyword {
            background-color: #fff143;
            font-weight: bold;         /* 文字加粗 */
            padding: 0 2px;            /* 可选：增加内边距，让背景更明显 */
        }
        /* 预览容器样式，固定高度避免页面错乱 */
        #previewContainer {
            width: 100%;
            height: 80vh; /* 占屏幕高度80% */
            border: 1px solid #eee;
            border-radius: 4px;
            overflow: hidden;
            position: relative;
        }
        /* 加载中/错误提示样式 */
        .loading, .error {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }
        .loading span, .error span {
            color: #666;
            font-size: 14px;
        }
        /* 图片预览适配 */
        #previewContainer img {
            width: 100%;
            height: 100%;
            object-fit: contain; /* 保持图片比例，不拉伸 */
        }
        /* iframe预览适配（PDF/Office文档） */
        #previewContainer iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
        /* 音视频预览适配 */
        #previewContainer video,
        #previewContainer audio {
            width: 100%;
            height: 100%;
            padding: 20px;
        }
        .action-icon.preview { background: #e0f7fa; color: #00acc1; }
    </style>
</head>
<body>
    <div class="file-container">

        <div class="file-list">
            <!-- 页面标题和批量操作按钮 -->
            <div class="page-header">
                <div class="breadcrumb" id="breadcrumb" style="display: block;">
                    <span class="breadcrumb-item active">全部文件</span>
                </div>
                <div class="batch-actions">
                    <div class="batch-info">
                        <span id="selectedCount">已选择 0 项</span>
                        <span id="pageSizeInfo" style="margin-left: 10px; color: #999; font-size: 12px;">每页显示: <span id="currentPageSize">13</span> 条</span>
                    </div>
                    <div class="action-buttons">
                        <div class="action-item" onclick="parent.openUploadModal()" data-tooltip="上传文件">
                            <button class="action-icon upload">📤</button>
                        </div>
                        <div class="action-item" onclick="openCreateFolderModal()" data-tooltip="新建文件夹">
                            <button class="action-icon create">📁</button>
                        </div>
                        <div class="action-item" onclick="batchDownload()" data-tooltip="下载">
                            <button class="action-icon download">📥</button>
                        </div>
                        <div class="action-item" onclick="batchDelete()" data-tooltip="删除">
                            <button class="action-icon delete">🗑️</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="file-list-wrapper">
                <table class="file-table">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" id="selectAll">
                            </th>
                            <th>文件名</th>
                            <th>大小</th>
                            <th>修改时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="fileTableBody">
                        <tr>
                            <td colspan="5" class="loading">
                                <div>正在加载文件列表...</div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="pagination" id="pagination" style="display: none;">
            <button class="page-btn" id="prevBtn">上一页</button>
            <span class="page-info" id="pageInfo">第 1 页，共 1 页</span>
            <button class="page-btn" id="nextBtn">下一页</button>
        </div>
    </div>

    <!-- 新建文件夹模态框 -->
    <div id="createFolderModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>新建文件夹</h3>
                <span class="close" onclick="closeCreateFolderModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="folderName">文件夹名称：</label>
                    <input type="text" id="folderName" placeholder="请输入文件夹名称" maxlength="50">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeCreateFolderModal()">取消</button>
                <button class="btn btn-primary" onclick="createFolder()">创建</button>
            </div>
        </div>
    </div>

    <!-- 重命名模态框 -->
    <div id="renameModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>重命名</h3>
                <span class="close" onclick="closeRenameModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="renameFileName">新名称：</label>
                    <input type="text" id="renameFileName" placeholder="请输入新名称" maxlength="100">
                    <input type="hidden" id="renameFileId">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeRenameModal()">取消</button>
                <button class="btn btn-primary" onclick="executeRename()">确定</button>
            </div>
        </div>
    </div>

    <!-- 预览模态框 -->
    <div id="previewModal" class="modal" style="display: none;">
        <div class="modal-content" style="width: 90%; max-width: 1200px; height: 90vh; max-height: 900px; padding: 0;">
            <div class="modal-header">
                <h3 id="previewModalTitle">文件预览</h3>
                <span class="close" onclick="closePreviewModal()">&times;</span>
            </div>
            <!-- 预览容器（放在模态框内） -->
            <div id="previewContainer" style="width: 100%; height: calc(100% - 60px); border: none; border-radius: 0;">
                <div class="loading">
                    <span>正在生成预览链接，请稍候...</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 分享设置模态框 -->
    <div id="shareModal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3>✨ 分享设置</h3>
                <span class="close" onclick="closeShareModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="share-form-item">
                    <label for="shareExpireTime">有效期</label>
                    <select id="shareExpireTime">
                        <option value="1">1天</option>
                        <option value="7" selected>7天</option>
                        <option value="30">30天</option>
                        <option value="0">永久有效</option>
                    </select>
                </div>
                <div class="share-form-item">
                    <label>密码保护</label>
                    <div class="checkbox-label">
                        <input type="checkbox" id="enablePassword">
                        <span>启用密码访问</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeShareModal()">取消</button>
                <button class="btn btn-primary" onclick="createShare()">创建分享</button>
            </div>
        </div>
    </div>
    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 13;  // 从10增加到13
        let totalPages = 1;
        let currentUserId = null; // 用户ID（从session获取）
        let currentParentId = 0; // 根目录
        let breadcrumbPath = []; // 面包屑路径
        
        // 将currentParentId设置为全局变量，供父窗口访问
        window.currentParentId = currentParentId;
        
        // 当前文件类型过滤
        let currentFileType = null;

        // 根据窗口大小计算每页显示数量
        function calculatePageSize() {
            const windowHeight = window.innerHeight;
            const windowWidth = window.innerWidth;
            
            // 计算可用高度（减去头部、分页等固定元素的高度）
            const headerHeight = 60; // 页面头部高度
            const paginationHeight = 80; // 分页区域高度
            const availableHeight = windowHeight - headerHeight - paginationHeight;
            
            // 计算每行高度（包括边框、内边距）
            const rowHeight = 50; // 每行大约50px高度
            
            // 计算可显示的行数
            const maxRows = Math.floor(availableHeight / rowHeight);
            
            // 根据窗口宽度调整
            let calculatedPageSize = maxRows;
            
            // 小屏幕设备优化
            if (windowWidth < 768) {
                calculatedPageSize = Math.min(maxRows, 6); // 从3增加到6
            } else if (windowWidth < 1200) {
                calculatedPageSize = Math.min(maxRows, 8); // 从5增加到8
            } else {
                calculatedPageSize = Math.min(maxRows, 11); // 从8增加到11
            }
            
            // 确保最小和最大值
            return Math.max(3, Math.min(calculatedPageSize, 20));
        }

        // 更新页面大小
        function updatePageSize() {
            const newPageSize = calculatePageSize();
            if (newPageSize !== pageSize) {
                pageSize = newPageSize;
                currentPage = 1; // 重置到第一页
                updatePageSizeDisplay(); // 更新显示
                loadFileList(); // 重新加载数据
            }
        }

        // 更新页面大小显示
        function updatePageSizeDisplay() {
            const currentPageSizeElement = document.getElementById('currentPageSize');
            if (currentPageSizeElement) {
                currentPageSizeElement.textContent = pageSize;
            }
        }

        // 检查登录状态并初始化
        async function initHomePage() {
            try {
                // 先检查登录状态
                const response = await fetch('/api/user/check-login');
                const result = await response.json();
                
                if (result.loggedIn && result.user) {
                    // 已登录：设置用户ID
                    currentUserId = result.user.id;
                    
                    // 如果父窗口存在，也更新父窗口的全局变量
                    if (window.parent && window.parent.CURRENT_USER_ID !== currentUserId) {
                        window.parent.CURRENT_USER_ID = currentUserId;
                    }
                    
                    // 初始化页面
                    pageSize = calculatePageSize();
                    updatePageSizeDisplay();
                    updateBreadcrumb();
                    loadFileList();
                    setupEventListeners();
                    initTooltips();
                } else {
                    // 未登录：如果是iframe，通知父窗口跳转；否则直接跳转
                    if (window.parent && window.parent !== window) {
                        window.parent.location.href = '/login';
                    } else {
                        window.location.href = '/login';
                    }
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
                // 检查失败时也跳转到登录页
                if (window.parent && window.parent !== window) {
                    window.parent.location.href = '/login';
                } else {
                    window.location.href = '/login';
                }
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 延迟一点，确保父窗口的登录检查完成
            setTimeout(() => {
                initHomePage();
            }, 100);
        });

        // 监听窗口大小变化
        let resizeTimeout;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(updatePageSize, 300); // 防抖，300ms后执行
        });

        // 设置事件监听器
        function setupEventListeners() {
            // 全选/取消全选
            const selectAllCheckbox = document.getElementById('selectAll');
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('.file-checkbox');
                    checkboxes.forEach(checkbox => {
                        checkbox.checked = this.checked;
                    });
                    updateBatchToolbar();
                });
            }

            // 监听单个复选框变化
            document.addEventListener('change', function(e) {
                if (e.target.classList.contains('file-checkbox')) {
                    updateBatchToolbar();
                }
            });

            // 分页按钮
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            
            if (prevBtn) {
                prevBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (currentPage > 1) {
                        currentPage--;
                        loadFileList();
                    }
                });
            }

            if (nextBtn) {
                nextBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    if (currentPage < totalPages) {
                        currentPage++;
                        loadFileList();
                    }
                });
            }

        }

        // 加载文件列表
        async function loadFileList() {
            try {
                const tbody = document.getElementById('fileTableBody');
                tbody.innerHTML = '<tr><td colspan="5" class="loading"><div>正在加载文件列表...</div></td></tr>';

                let url = `/api/userfile/list?pageSize=${pageSize}&pageNo=${currentPage}&userId=${currentUserId}&parentId=${currentParentId}`;
                if (currentFileType) {
                    url += `&fileType=${currentFileType}`;
                }

                const response = await fetch(url);
                const result = await response.json();

                if (result.success) {
                    renderFileList(result.data);
                } else {
                    showError('加载文件列表失败: ' + result.message);
                }
            } catch (error) {
                console.error('加载文件列表失败:', error);
                showError('网络错误，请稍后重试');
            }
        }

        // 渲染文件列表
        function renderFileList(data) {
            const tbody = document.getElementById('fileTableBody');
            const pagination = document.getElementById('pagination');

            if (!data || !data.list || data.list.length === 0) {
                // 空状态处理（不变）
                tbody.innerHTML = `
            <tr>
                <td colspan="5" class="empty-state">
                    <div class="empty-icon">📁</div>
                    <div>暂无文件</div>
                </td>
            </tr>
        `;
                pagination.style.display = 'none';
                return;
            }

            // 更新分页信息（不变）
            currentPage = data.pageNum || 1;
            totalPages = data.pages || 1;
            updatePagination();

            // 将文件列表保存到全局变量
            window.fileList = data.list;

            // 渲染文件列表（重点修改文件名部分）
            tbody.innerHTML = '';
            data.list.forEach(file => {
                const row = document.createElement('tr');
                const isDirectory = file.isDirectory === 1 || file.isDirectory === true;
                // 优先取高亮文件名，无则取原始文件名
                const displayName = file.highlightFileName || file.fileName || '未知文件';
                const fileSize = isDirectory ? '-' : formatFileSize(file.fileSize);
                const clickHandler = isDirectory ? `enterFolder(${file.id}, '${file.fileName}')` : '';
                const cursorStyle = isDirectory ? 'cursor: pointer;' : '';

                // 1. 渲染行结构：给文件名div加 data-file-name 标识，暂不填内容
                row.innerHTML = `
            <td>
                <input type="checkbox" class="file-checkbox" data-id="${file.id}">
            </td>
            <td onclick="${clickHandler}" style="${cursorStyle}">
                <div class="file-item">
                    <div class="file-icon">${getFileIcon(file.fileName, file.isDirectory)}</div>
                    <!-- 关键：加 data-file-name 标识，内容先空着 -->
                    <div class="file-name" data-file-name="true"></div>
                </div>
            </td>
            <td>
                <div class="file-size">${fileSize}</div>
            </td>
            <td>
                <div class="file-date">${formatDate(file.updateTime)}</div>
            </td>
            <td>
                <div class="file-actions">
                    ${isDirectory ? '' : `
                    <div class="action-item" onclick="downloadFile(${file.id})" data-tooltip="下载"><button class="action-icon download">📥</button></div>
                    <div class="action-item" onclick="previewFile('${file.filePath}')" data-tooltip="预览"><button class="action-icon preview">👁️</button></div>
                    `}
                    <div class="action-item" onclick="openRenameModal(${file.id}, '${file.fileName}')" data-tooltip="重命名"><button class="action-icon rename">✏️</button></div>
                    <div class="action-item" onclick="shareFile(${file.id}, '${file.fileName}')" data-tooltip="分享"><button class="action-icon share">🔗</button></div>
                    <div class="action-item" onclick="deleteFile(${file.id})" data-tooltip="删除"><button class="action-icon delete">🗑️</button></div>
                </div>
            </td>
        `;
                tbody.appendChild(row);

                // 2. 用原生JS找到当前行的文件名div，通过 innerHTML 赋值（解析高亮标签）
                const fileNameDiv = row.querySelector('[data-file-name="true"]');
                if (fileNameDiv) {
                    fileNameDiv.innerHTML = displayName; // 关键：原生JS用 innerHTML 渲染HTML内容
                }
            });

            pagination.style.display = 'flex';
            initTooltips();
        }

        window.renderFileList = renderFileList;

        // 更新分页信息
        function updatePagination() {
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            const pageInfo = document.getElementById('pageInfo');

            if (prevBtn && nextBtn && pageInfo) {
                prevBtn.disabled = currentPage <= 1;
                nextBtn.disabled = currentPage >= totalPages;
                pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
            }
        }

        // 获取文件图标
        function getFileIcon(fileName, isDirectory) {
            if (!fileName) return '📄';
            
            // 如果是目录，返回目录图标
            if (isDirectory === 1 || isDirectory === true) {
                return '📁';
            }
            
            const ext = fileName.split('.').pop().toLowerCase();
            const iconMap = {
                'pdf': '📄',
                'doc': '📝', 'docx': '📝',
                'xls': '📊', 'xlsx': '📊',
                'ppt': '📋', 'pptx': '📋',
                'txt': '📄',
                'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️',
                'mp4': '🎥', 'avi': '🎥', 'mov': '🎥',
                'mp3': '🎵', 'wav': '🎵',
                'zip': '📦', 'rar': '📦', '7z': '📦',
                'folder': '📁'
            };
            
            return iconMap[ext] || '📄';
        }

        function formatFileSize(size) {
            // 情况1：参数是字符串且已包含单位（如"13.5KB"），直接返回
            if (typeof size === 'string' && /^[0-9.]+(\s*[BKMG]B|B)$/i.test(size)) {
                return size;
            }

            // 情况2：参数是数字（原始字节数），计算并格式化
            if (typeof size === 'number' && !isNaN(size) && size >= 0) {
                const units = ['B', 'KB', 'MB', 'GB'];
                let unitIndex = 0;
                let formattedSize = size;
                while (formattedSize >= 1024 && unitIndex < units.length - 1) {
                    formattedSize /= 1024;
                    unitIndex++;
                }
                return formattedSize.toFixed(1) + ' ' + units[unitIndex];
            }

            // 情况3：参数无效，返回默认值
            return '-';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '-';
            
            try {
                const date = new Date(dateString);
                return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
            } catch (error) {
                return dateString;
            }
        }

        // 下载文件
        async function downloadFile(fileId) {
            try {
                // 先通过userfile.id获取filebase.id
                const userFileResponse = await fetch(`/api/userfile/${fileId}`);
                const userFileResult = await userFileResponse.json();
                
                if (!userFileResult.success) {
                    alert('获取文件信息失败：' + userFileResult.message);
                    return;
                }
                
                const userFile = userFileResult.data;
                const fileBaseId = userFile.fileBaseId;
                
                if (!fileBaseId) {
                    alert('文件信息不完整，无法下载');
                    return;
                }
                
                // 使用filebase.id调用下载接口
                const downloadUrl = `/api/filebase/download/${fileBaseId}`;
                
                // 创建隐藏的下载链接
                const link = document.createElement('a');
                link.href = downloadUrl;
                link.style.display = 'none';
                link.download = '';
                
                document.body.appendChild(link);
                link.click();
                
                // 延迟移除链接
                setTimeout(() => {
                    document.body.removeChild(link);
                }, 1000);
                
            } catch (error) {
                console.error('下载失败:', error);
                alert('下载失败，请稍后重试');
            }
        }

        // 进入目录
        function enterFolder(folderId, folderName) {
            // 更新当前父目录ID
            currentParentId = folderId;
            window.currentParentId = currentParentId; // 更新全局变量
            currentPage = 1;
            
            // 更新面包屑路径
            breadcrumbPath.push({id: folderId, name: folderName});
            updateBreadcrumb();
            
            // 更新主面包屑导航 - 显示完整路径
            updateBreadcrumbNav();
            
            // 重新加载文件列表
            loadFileList();
        }
        
        // 返回根目录
        function goToRoot() {
            currentParentId = 0;
            window.currentParentId = currentParentId; // 更新全局变量
            currentPage = 1;
            breadcrumbPath = [];
            updateBreadcrumb();
            
            // 更新主面包屑导航 - 显示完整路径
            updateBreadcrumbNav();
            
            loadFileList();
        }
        
        // 返回上一级目录
        function goToParent() {
            if (breadcrumbPath.length > 0) {
                breadcrumbPath.pop();
                if (breadcrumbPath.length === 0) {
                    goToRoot();
                } else {
                    const parent = breadcrumbPath[breadcrumbPath.length - 1];
                    currentParentId = parent.id;
                    window.currentParentId = currentParentId; // 更新全局变量
                    currentPage = 1;
                    updateBreadcrumb();
                    
                    // 更新主面包屑导航 - 显示完整路径
                    updateBreadcrumbNav();
                    
                    loadFileList();
                }
            }
        }
        
        // 更新面包屑显示
        function updateBreadcrumb() {
            const breadcrumb = document.getElementById('breadcrumb');
            if (breadcrumbPath.length === 0) {
                // 在根目录时显示"全部文件"
                breadcrumb.style.display = 'block';
                breadcrumb.innerHTML = '<span class="breadcrumb-item active">全部文件</span>';
            } else {
                // 在子目录时显示完整路径
                breadcrumb.style.display = 'block';
                let html = '<span class="breadcrumb-item" onclick="goToRoot()">全部文件</span>';
                
                breadcrumbPath.forEach((item, index) => {
                    html += '<span class="breadcrumb-separator">/</span>';
                    html += `<span class="breadcrumb-item" onclick="goToBreadcrumb(${index})">${item.name}</span>`;
                });
                
                breadcrumb.innerHTML = html;
            }
        }
        
        // 文件类型过滤函数
        function filterByFileType(fileType) {
            currentFileType = fileType;
            currentPage = 1;
            loadFileList();
            // 类型过滤时也保持显示层级路径
            updateBreadcrumbNav();
        }
        
        // 将函数暴露给父窗口
        window.filterByFileType = filterByFileType;
        
        // 更新面包屑导航（供父窗口调用）
        function updateBreadcrumbNav(currentPath) {
            const breadcrumb = document.getElementById('breadcrumb');
            if (breadcrumb) {
                breadcrumb.style.display = 'block';
                console.log('iframe收到面包屑更新:', currentPath); // 调试日志
                
                // 如果传入了currentPath参数，直接使用该参数
                if (currentPath) {
                    breadcrumb.innerHTML = `<span class="breadcrumb-item active">${currentPath}</span>`;
                } else {
                    // 如果没有传入参数，使用原有的逻辑
                    if (breadcrumbPath.length === 0) {
                        breadcrumb.innerHTML = '<span class="breadcrumb-item active">全部文件</span>';
                    } else {
                        // 如果当前在子目录，显示完整路径
                        let html = '<span class="breadcrumb-item" onclick="goToRoot()">全部文件</span>';
                        breadcrumbPath.forEach((item, index) => {
                            html += '<span class="breadcrumb-separator">/</span>';
                            html += `<span class="breadcrumb-item" onclick="goToBreadcrumb(${index})">${item.name}</span>`;
                        });
                        breadcrumb.innerHTML = html;
                    }
                }
            }
        }
        
        // 将函数暴露给父窗口
        window.updateBreadcrumbNav = updateBreadcrumbNav;
        window.performSearch = performSearch;
        window.applyAdvancedSearch = applyAdvancedSearch;
        window.openRenameModal = openRenameModal;
        window.closeRenameModal = closeRenameModal;
        window.executeRename = executeRename;
        
        // 点击面包屑导航
        function goToBreadcrumb(index) {
            // 截取到指定索引的路径
            breadcrumbPath = breadcrumbPath.slice(0, index + 1);
            
            if (breadcrumbPath.length === 0) {
                goToRoot();
            } else {
                const target = breadcrumbPath[breadcrumbPath.length - 1];
                currentParentId = target.id;
                window.currentParentId = currentParentId; // 更新全局变量
                currentPage = 1;
                updateBreadcrumb();
                
                // 更新主面包屑导航 - 显示完整路径
                updateBreadcrumbNav();
                
                loadFileList();
            }
        }

        // 删除文件（软删除至回收站）
        async function deleteFile(fileId) {
            if (!confirm('确定要删除这个文件吗？该操作会将文件移至回收站。')) return;

            try {
                const resp = await fetch(`/api/filebase/${fileId}`, { method: 'DELETE' });
                if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
                const json = await resp.json();
                if (!json.success) throw new Error(json.message || '删除失败');

                // 刷新当前列表
                await loadFileList();
                // 同步刷新侧边栏用量（父页面暴露的函数）
                if (parent && parent.refreshStorageInfo) {
                    parent.refreshStorageInfo();
                }
                alert('已移动到回收站');
            } catch (e) {
                alert('删除失败：' + e.message);
            }
        }

        // 显示错误信息
        function showError(message) {
            const tbody = document.getElementById('fileTableBody');
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="empty-state">
                        <div class="empty-icon">❌</div>
                        <div>${message}</div>
                    </td>
                </tr>
            `;
        }

        // 更新批量操作工具栏
        function updateBatchToolbar() {
            const selectedCheckboxes = document.querySelectorAll('.file-checkbox:checked');
            const selectedCount = document.getElementById('selectedCount');
            selectedCount.textContent = `已选择 ${selectedCheckboxes.length} 项`;
        }

        // 初始化悬浮提示功能
        function initTooltips() {
            const actionItems = document.querySelectorAll('.action-item');
            actionItems.forEach(item => {
                // 检查是否已经绑定了事件监听器
                if (item.hasAttribute('data-tooltip-initialized')) {
                    return; // 跳过已经初始化的元素
                }
                
                let hoverTimer;
                
                item.addEventListener('mouseenter', function() {
                    hoverTimer = setTimeout(() => {
                        this.classList.add('show-tooltip');
                    }, 500); // 0.5秒延迟
                });
                
                item.addEventListener('mouseleave', function() {
                    clearTimeout(hoverTimer);
                    this.classList.remove('show-tooltip');
                });
                
                // 标记为已初始化
                item.setAttribute('data-tooltip-initialized', 'true');
            });
        }

        // 获取选中的文件ID列表
        function getSelectedFileIds() {
            const selectedCheckboxes = document.querySelectorAll('.file-checkbox:checked');
            return Array.from(selectedCheckboxes).map(checkbox => checkbox.dataset.id);
        }

        // 批量下载
        async function batchDownload() {
            const selectedIds = getSelectedFileIds();
            if (selectedIds.length === 0) {
                alert('请先选择要下载的文件');
                return;
            }

            try {
                // 过滤出非目录的文件
                const fileIds = selectedIds.filter(id => {
                    const file = window.fileList ? window.fileList.find(f => f.id == id) : null;
                    const isDirectory = file && (file.isDirectory === 1 || file.isDirectory === true);
                    return file && !isDirectory;
                });

                if (fileIds.length === 0) {
                    alert('选中的都是文件夹，无法下载');
                    return;
                }

                // 逐个下载文件
                for (let i = 0; i < fileIds.length; i++) {
                    const fileId = fileIds[i];
                    setTimeout(() => {
                        downloadFile(fileId);
                    }, i * 500);
                }

            } catch (error) {
                console.error('批量下载失败:', error);
                alert('批量下载失败，请稍后重试');
            }
        }

        // 批量删除
        async function batchDelete() {
            const selectedIds = getSelectedFileIds();
            if (selectedIds.length === 0) {
                alert('请先选择要删除的文件');
                return;
            }

            if (!confirm(`确定要删除选中的 ${selectedIds.length} 个文件吗？该操作会将文件移至回收站。`)) return;

            try {
                const promises = selectedIds.map(id => 
                    fetch(`/api/filebase/${id}`, { method: 'DELETE' })
                        .then(resp => resp.json())
                );
                
                const results = await Promise.all(promises);
                const successCount = results.filter(r => r.success).length;
                
                if (successCount === selectedIds.length) {
                    alert(`成功删除 ${successCount} 个文件`);
                } else {
                    alert(`删除完成，成功 ${successCount} 个，失败 ${selectedIds.length - successCount} 个`);
                }
                
                await loadFileList();
                if (parent && parent.refreshStorageInfo) { parent.refreshStorageInfo(); }
            } catch (error) {
                alert('批量删除失败：' + error.message);
            }
        }

        // --- 搜索功能 ---
        // 执行搜索
        function performSearch(keyword) {
            // 直接调用父窗口（index.html）的真实搜索函数，不做本地模拟
            if (parent && typeof parent.performSearch === 'function') {
                parent.performSearch(keyword);
            } else {
                console.error('父窗口未暴露 performSearch 函数');
            }
        }

        // 应用高级搜索
        function applyAdvancedSearch(params) {
            // 直接调用父窗口的真实高级搜索函数
            if (parent && typeof parent.applyAdvancedSearch === 'function') {
                parent.applyAdvancedSearch(params);
            } else {
                console.error('父窗口未暴露 applyAdvancedSearch 函数');
            }
        }

        // 辅助函数：将文件大小字符串转换为字节数
        function getSizeInBytes(sizeStr) {
            if (!sizeStr || sizeStr === '-') return 0;
            
            const num = parseFloat(sizeStr);
            if (sizeStr.includes('KB')) return num * 1024;
            if (sizeStr.includes('MB')) return num * 1024 * 1024;
            if (sizeStr.includes('GB')) return num * 1024 * 1024 * 1024;
            return num;
        }
        // --- 重命名功能 ---
        // 打开重命名模态框
        function openRenameModal(fileId, currentName) {
            document.getElementById('renameFileId').value = fileId;
            document.getElementById('renameFileName').value = currentName;
            document.getElementById('renameModal').style.display = 'flex';
            
            // 选中输入框中的文本（去掉扩展名）
            const input = document.getElementById('renameFileName');
            setTimeout(() => {
                input.focus();
                const lastDotIndex = currentName.lastIndexOf('.');
                if (lastDotIndex > 0) {
                    input.setSelectionRange(0, lastDotIndex);
                } else {
                    input.select();
                }
            }, 100);
        }

        // 关闭重命名模态框
        function closeRenameModal() {
            document.getElementById('renameModal').style.display = 'none';
            document.getElementById('renameFileName').value = '';
            document.getElementById('renameFileId').value = '';
        }

        // 执行重命名
        async function executeRename() {
            // 确保用户ID已获取
            if (!currentUserId) {
                alert('用户未登录，请先登录');
                window.location.href = '/login';
                return;
            }
            
            const fileId = document.getElementById('renameFileId').value;
            const newName = document.getElementById('renameFileName').value.trim();
            
            console.log('重命名参数 - fileId:', fileId, 'newName:', newName, 'userId:', currentUserId);
            
            if (!newName) {
                alert('请输入新名称');
                return;
            }
            
            // 验证名称格式
            if (newName.includes('/') || newName.includes('\\') || newName.includes(':') || 
                newName.includes('*') || newName.includes('?') || newName.includes('"') || 
                newName.includes('<') || newName.includes('>') || newName.includes('|')) {
                alert('名称包含非法字符');
                return;
            }
            
            try {
                const response = await fetch('/api/userfile/rename', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `fileId=${fileId}&newName=${encodeURIComponent(newName)}&userId=${currentUserId}`
                });
                
                const result = await response.json();
                
                console.log('重命名响应:', result); // 添加调试信息
                
                if (result.success) {
                    alert('重命名成功');
                    closeRenameModal();
                    // 重新加载文件列表
                    await loadFileList();
                } else {
                    alert('重命名失败：' + result.message);
                }
            } catch (error) {
                console.error('重命名失败:', error);
                alert('重命名失败：' + error.message);
            }
        }

        // 打开新建文件夹模态框
        function openCreateFolderModal() {
            document.getElementById('createFolderModal').style.display = 'flex';
            document.getElementById('folderName').value = '';
            document.getElementById('folderName').focus();
        }

        // 关闭新建文件夹模态框
        function closeCreateFolderModal() {
            document.getElementById('createFolderModal').style.display = 'none';
        }

        // 创建文件夹
        async function createFolder() {
            // 确保用户ID已获取
            if (!currentUserId) {
                alert('用户未登录，请先登录');
                window.location.href = '/login';
                return;
            }
            
            const folderName = document.getElementById('folderName').value.trim();
            
            if (!folderName) {
                alert('请输入文件夹名称');
                return;
            }
            
            try {
                const response = await fetch('/api/userfile/create-folder', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `folderName=${encodeURIComponent(folderName)}&userId=${currentUserId}&parentId=${currentParentId}`
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('文件夹创建成功');
                    closeCreateFolderModal();
                    loadFileList(); // 重新加载文件列表
                } else {
                    alert('创建失败：' + result.message);
                }
            } catch (error) {
                alert('创建失败：' + error.message);
            }
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const createModal = document.getElementById('createFolderModal');
            const renameModal = document.getElementById('renameModal');
            
            if (event.target === createModal) {
                closeCreateFolderModal();
            }
            if (event.target === renameModal) {
                closeRenameModal();
            }
        }

        // 回车键创建文件夹
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Enter' && document.getElementById('createFolderModal').style.display === 'flex') {
                createFolder();
            }
        });

        // 1. 新增：预览函数（点击预览按钮时调用）
        function previewFile(filePath) {
            // 显示预览模态框
            document.getElementById("previewModal").style.display = "flex";
            // 更新模态框标题（显示当前预览文件名）
            document.getElementById("previewModalTitle").textContent = `文件预览：${filePath.split("/").pop()}`;
            // 调用后端接口获取签名预览URL（使用你的项目基础路径）
            const baseUrl = "http://111.228.49.86:8080/"; // 确保与你的后端地址一致
            $.ajax({
                url: `${baseUrl}/api/filebase/getPreviewUrl`,
                type: "GET",
                data: { filePath: filePath }, // 传递当前文件的OSS路径（与后端接口参数匹配）
                dataType: "json",
                success: function (res) {
                    if (res.code === "200") {
                        const previewUrl = res.previewUrl;
                        const fileType = res.fileType;
                        // 渲染预览内容
                        renderPreview(previewUrl, fileType);
                        console.log(filePath,fileType,previewUrl);
                    } else {
                        const container = document.getElementById("previewContainer");
                        container.innerHTML = `
                    <div class="error">
                        <span>${res.msg || "生成预览链接失败，请重试"}</span>
                    </div>
                `;
                    }
                },
                error: function (xhr, status, error) {
                    const container = document.getElementById("previewContainer");
                    container.innerHTML = `
                <div class="error">
                    <span>预览接口访问失败：${error}</span>
                    <br>
                    <span style="margin-top:5px;display:inline-block;">请检查接口地址是否正确，或是否存在跨域问题</span>
                </div>
            `;
                }
            });
        }

        // 2. 新增：关闭预览模态框
        function closePreviewModal() {
            document.getElementById("previewModal").style.display = "none";
            // 清空预览容器，避免下次打开有残留
            document.getElementById("previewContainer").innerHTML = `
        <div class="loading">
            <span>正在生成预览链接，请稍候...</span>
        </div>
    `;
        }

        /**
         * 4. 根据文件类型渲染不同的预览组件
         * @param {string} url - 后端返回的签名预览URL
         * @param {string} type - 后端返回的文件后缀（小写）
         */
        function renderPreview(url, type) {
            const container = document.getElementById("previewContainer");
            container.innerHTML = ""; // 清空加载状态

            switch (type) {
                // 图片类型
                case "jpg": case "jpeg": case "png": case "gif": case "webp": case "bmp":
                    container.innerHTML = `<img src="${url}" alt="图片预览" title="点击可查看原图" style="width:100%;height:100%;object-fit:contain;">`;
                    break;
                // PDF类型
                /*case "pdf":
                    container.innerHTML = `<iframe src="${url}" title="PDF预览" style="width:100%;height:100%;border:none;"></iframe>`;
                    break;*/
                // 视频类型
                case "mp4":
                case "webm":
                case "mov":
                case "avi":
                case "mkv":
                    container.innerHTML = `
                <video controls autoplay muted playsinline style="width:100%;height:100%;padding:20px;">
                    <source src="${url}" type="video/${type}">
                    您的浏览器不支持该视频格式，请下载后查看
                </video>
            `;
                    break;
                // 音频类型
                case "mp3": case "wav": case "ogg": case "flac":
                    container.innerHTML = `
                <audio controls autoplay style="width:100%;padding:20px;">
                    <source src="${url}" type="audio/${type}">
                    您的浏览器不支持该音频格式，请下载后查看
                 </audio>
            `;
                    break;
                // Office文档（依赖kkFileView）
                case "doc": case "docx": case "xls": case "xlsx": case "ppt": case "pptx":case "pdf":
                case "txt": case "md": case "json": case "xml": case "html": case "css": case "js":
                case "xmind":case "vsd":case "py":case "eml":case "psd":case "csv":
                    const kkFileViewUrl = "http://101.42.40.144:8012";
                    //const encodedUrl = encodeURIComponent(Base64.encode(url));
                    const encodedUrl = encodeURIComponent(Base64.encode(url).replace(/[\r\n]/g, '')).replace(/%0A/g, '');
                    const previewUrl = `${kkFileViewUrl}/onlinePreview?url=${encodedUrl}`;
                    console.log("office预览地址：",previewUrl);
                    container.innerHTML = `
                    <iframe
                        src="${previewUrl}"
                        title="Office文档预览"
                        style="width:100%;height:100%;border:none;"
                       onload="document.getElementById('officeLoading').style.display='none';this.style.display='block'">
                    </iframe>
                `;
                    break;
                // 其他类型
                default:
                    showDownloadTip(container, url, type);
            }
        }


        function showDownloadTip(container, url, fileType) {
            container.innerHTML = `
        <div class="download-tip" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;">
            <span>当前文件类型（.${fileType || "未知"}）不支持在线预览</span>
            <br>
        </div>
    `;
        }

        // 分享文件功能
        function shareFile(fileId, fileName) {
            // 设置当前分享的文件信息
            window.currentShareFileId = fileId;
            window.currentShareFileName = fileName;
            
            // 重置表单
            document.getElementById('shareExpireTime').value = '7';
            document.getElementById('enablePassword').checked = false;
            
            // 显示分享设置弹窗
            document.getElementById('shareModal').style.display = 'flex';
        }

        // 关闭分享设置弹窗
        function closeShareModal() {
            document.getElementById('shareModal').style.display = 'none';
        }

        // 创建分享
        async function createShare() {
            try {
                const expireDays = parseInt(document.getElementById('shareExpireTime').value);
                const enablePassword = document.getElementById('enablePassword').checked;

                // 计算过期时间
                let expireTime = null;
                if (expireDays > 0) {
                    const expireDate = new Date();
                    expireDate.setDate(expireDate.getDate() + expireDays);
                    expireTime = expireDate.toISOString();
                }

                // 构建请求数据（只传递是否启用密码的标识，不传递具体的密码值）
                // 确保用户ID已获取
                if (!currentUserId) {
                    alert('用户未登录，请先登录');
                    window.location.href = '/login';
                    return;
                }
                
                const requestData = {
                    fileId: window.currentShareFileId,
                    shareTitle: window.currentShareFileName,
                    userId: currentUserId,
                    expireTime: expireTime,
                    enablePassword: enablePassword
                };

                // 调用后端创建分享链接
                const response = await fetch('/api/share/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(requestData)
                });

                const result = await response.json();

                if (result.success) {
                    // 生成分享链接
                    const shareUrl = `${window.location.origin}/share/${result.data.shareCode}`;
                    
                    // 获取后端返回的密码（如果有）
                    const generatedPassword = result.data.password || '';
                    
                    // 复制到剪贴板
                    await navigator.clipboard.writeText(shareUrl);
                    
                    // 关闭弹窗
                    closeShareModal();
                    
                    // 构建提示信息
                    let alertMsg = `分享链接已复制到剪贴板！\n\n分享链接：${shareUrl}\n\n有效期：${expireDays === 0 ? '永久有效' : expireDays + '天'}`;
                    
                    // 如果启用了密码保护，显示系统生成的密码
                    if (enablePassword && generatedPassword) {
                        alertMsg += `\n\n密码保护：已启用\n访问密码：${generatedPassword}`;
                    } else {
                        alertMsg += `\n\n密码保护：未启用`;
                    }
                    
                    alert(alertMsg);
            } else {
                    alert('创建分享失败：' + result.message);
                }
            } catch (error) {
                console.error('分享失败:', error);
                alert('分享失败，请稍后重试');
            }
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const createModal = document.getElementById('createFolderModal');
            const renameModal = document.getElementById('renameModal');
            const previewModal = document.getElementById('previewModal');
            const shareModal = document.getElementById('shareModal');
            
            if (event.target === createModal) closeCreateFolderModal();
            if (event.target === renameModal) closeRenameModal();
            if (event.target === previewModal) closePreviewModal();
            if (event.target === shareModal) closeShareModal();
        }

        document.addEventListener('click', function() {
            // 向父页面（index.html）发送关闭指令
            parent.postMessage('closeSuggestPanel', '*');
        });
    </script>
</body>
</html>